package com.xy.job.executor.core.server

import com.xy.job.core.api.request.HeartbeatParam
import com.xy.job.executor.config.ExecutorProperties
import com.xy.job.executor.core.client.IAdminClient
import org.slf4j.LoggerFactory
import java.util.concurrent.TimeUnit

class RegisterThread(
    private val adminClient: IAdminClient,
    private val executorProperties: ExecutorProperties,
) : Thread() {

    @Volatile
    private var running = true

    private val log = LoggerFactory.getLogger(this::class.java)

    override fun run() {
        while (running) {
            try {
                val param = HeartbeatParam(
                    groupCode = executorProperties.groupCode,
                    host = executorProperties.ip,
                    port = executorProperties.port.toInt(),
                )
                val heartbeat = adminClient.heartbeat(param)
                if (heartbeat.success && heartbeat.data == true) {
                    log.debug("send heartbeat success")
                } else {
                    log.error("send heartbeat failed, message={}", heartbeat.message)
                }
            } catch (e: Throwable) {
                log.error("send heartbeat failed, message={}", e.message, e)
            }
            TimeUnit.SECONDS.sleep(5)
        }
    }

    override fun start() {
        super.start()
        log.info("registerThread start")
    }

    fun cancel() {
        running = false
        log.info("registerThread stop")
    }
}